package com.example.l10_yanweicheng.recognition;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;

import java.net.URLEncoder;
import java.util.List;

/**

 * 人体检测和属性识别
 */
public class BodyAttr {

    /**

     * 重要提示代码中所需工具类

     * FileUtil,Base64Util,HttpUtil,GsonUtils请从

     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72

     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2

     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3

     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3

     * 下载
     */
    public static String body_attr(String filePath) {

        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_attr";
        try {
            // 本地文件路径
//            String filePath = "F:\\1.jpg";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam + "&" + "type=face_mask";
//            String param2 = "type=" + "face_mask";

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = AuthService.getAuth();

            String result = HttpUtil.post(url, accessToken,param);
            System.out.println(result);
            return result;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String result = BodyAttr.body_attr("F:\\1.jpg");
        JsonObject jsonObject = (JsonObject)new JsonParser().parse(result);
        Gson gson = new Gson();
        java.lang.reflect.Type type = new TypeToken<RecognitionInfo>(){}.getType();
        RecognitionInfo recognitionInfo = gson.fromJson(jsonObject,type);
        List<RecognitionInfo.PersonInfo> results = recognitionInfo.person_info;
        System.out.println(results.size());
        for (int i = 0; i < results.size(); i++) {
            System.out.println("face_mask"+results.get(i).attributes.face_mask.name);
            System.out.println("location_top"+results.get(i).location.top);
        }
//        System.out.println(jsonObject.get("face_mask"));
    }
}